﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Queries.RegionTypes.GetOne;

public class GetOneRegionTypesQueryHandler : IRequestHandler<GetOneRegionTypesQueryRequest, GetOneRegionTypesQueryResponse>
{
    private readonly IMapper _mapper;
    private readonly IRegionTypeRepository _regionTypeRepository;

    public GetOneRegionTypesQueryHandler(IMapper mapper, IRegionTypeRepository regionTypeRepository)
    {
        _mapper = mapper;
        _regionTypeRepository = regionTypeRepository;
    }

    public async Task<GetOneRegionTypesQueryResponse> Handle(GetOneRegionTypesQueryRequest request, CancellationToken cancellationToken)
    {
        var regionType = await _regionTypeRepository.FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken);
        if (regionType == null) throw new NotFoundException($"Тип региона с id '{request.Id}' не найден");

        return _mapper.Map<GetOneRegionTypesQueryResponse>(regionType);
    }
}